#201806140057 大数据1802 陈沛杰
import numpy as np
import pandas as pd
from .GM11 import GM11 #引入自编的灰色预测函数  GM11相关源代码请放到当前代码同级目录中
def GM11(x0): #自定义灰色预测函数
  import numpy as np
  x1 = x0.cumsum() #1-AGO序列
  z1 = (x1[:len(x1)-1] + x1[1:])/2.0 #紧邻均值（MEAN）生成序列
  z1 = z1.reshape((len(z1),1))
  B = np.append(-z1, np.ones_like(z1), axis = 1)
  Yn = x0[1:].reshape((len(x0)-1, 1))
  [[a],[b]] = np.dot(np.dot(np.linalg.inv(np.dot(B.T, B)), B.T), Yn) #计算参数
  f = lambda k: (x0[0]-b/a)*np.exp(-a*(k-1))-(x0[0]-b/a)*np.exp(-a*(k-2)) #还原值
  delta = np.abs(x0 - np.array([f(i) for i in range(1,len(x0)+1)]))
  C = delta.std()/x0.std()
  P = 1.0*(np.abs(delta - delta.mean()) < 0.6745*x0.std()).sum()/len(x0)
  return f, a, b, x0[0], C, P #返回灰色预测函数、a、b、首项、方差比、小残差概率

inputfile = './new_income_tax.csv'
inputfile1 = './income_tax.csv'
new_income_tax = pd.read_csv(inputfile) # 读取经过特征选择后的数据
data = pd.read_csv(inputfile1) #读取总的数据
#new_income_tax.index = data.loc[:,'year']
new_income_tax.index = range(2004, 2016)
new_income_tax.loc[2016] = None
new_income_tax.loc[2017] = None
l = ['x1', 'x3', 'x4', 'x5', 'x9','x10']
for i in l:
  f = GM11(new_income_tax.loc[range(2004, 2016),i].values)[0]
  new_income_tax.loc[2016,i] = f(len(new_income_tax)-1)#2016年预测结果
  new_income_tax.loc[2017,i] = f(len(new_income_tax)) ##2017年预测结果
  new_income_tax[i] = new_income_tax[i].round(2) ## 保留两位小数
outputfile = './new_income_tax_GM11.xls' ## 灰色预测后保存的路径
y = list(data['y'].values) #提取企业所得税入列，合并至新数据框中
y.extend([np.nan,np.nan])
new_income_tax['y'] = y
new_income_tax.to_excel(outputfile) #结果输出
print('预测结果为：','\n',new_income_tax.loc[2016:2017,:]) ##预测结果展示


import pandas as pd
import numpy as np
from sklearn.svm import LinearSVR
import matplotlib.pyplot as plt
from sklearn.metrics import explained_variance_score,\
mean_absolute_error,mean_squared_error,\
median_absolute_error,r2_score
inputfile = './实验六/new_income_tax_GM11.xls' #灰色预测后保存的路径
data = pd.read_excel(inputfile) #读取数据
feature = ['x1', 'x3', 'x4', 'x5', 'x9','x10']

data_train = data.loc[0:11,:] #data.iloc[0:12,:] 此行语句类似上行功能
data_mean = data_train.mean()
data_std = data_train.std()
data_train = (data_train - data_mean)/data_std #数据标准化
x_train = data_train[feature].values #特征数据
y_train = data_train['y'].values #标签数据
linearsvr = LinearSVR()   #调用LinearSVR()函数
linearsvr.fit(x_train,y_train)
x = ((data[feature] - data_mean[feature])/ data_std[feature]).values  #预测，并还原结果。
data[u'y_pred'] = linearsvr.predict(x) * data_std['y'] + data_mean['y']
## SVR预测后保存的结果
outputfile = './实验六/new_income_tax_GM11_final.xls'
data.to_excel(outputfile)
print('真实值与预测值分别为：','\n',data[['y','y_pred']])

#绘制图形
x=np.arange(2004,2018)
#plt.xlim((2004,2018))
#x1=np.arange(2004,2016)
#x2=np.arange(2004,2018)
p=plt.figure()
p.add_subplot(2,1,1)
plt.plot(x,data['y'],'ro-')
p.add_subplot(2,1,2)
plt.plot(x,data['y_pred'],'bo-')

#附加实验：回归模型评价
print('企业所得税回归模型的平均绝对误差为：',
      mean_absolute_error(data.loc[0:11,'y'],data.loc[0:11,'y_pred']))
print('企业所得税回归模型的均方误差为：',
     mean_squared_error(data.loc[0:11,'y'],data.loc[0:11,'y_pred']))
print('企业所得税回归模型的中值绝对误差为：',
     median_absolute_error(data.loc[0:11,'y'],data.loc[0:11,'y_pred']))
print('企业所得税回归模型的可解释方差值为：',
     explained_variance_score(data.loc[0:11,'y'],data.loc[0:11,'y_pred']))
print('企业所得税回归模型的R方值为：',
     r2_score(data.loc[0:11,'y'],data.loc[0:11,'y_pred']))